package com.stone.service;

import com.stone.model.EmailRequest;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.mail.internet.MimeMessage;
import java.io.File;

@Service
public class EmailService {

    @Resource
    private JavaMailSender mailSender;

    /**
     * 发送简单文本文件
     */
    public void sendSimpleEmail(EmailRequest request) {
        try {
            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom("18108402266@163.com");
            // 国内临时邮箱地址: http://24mail.chacuo.net/
            message.setTo("rctxiw63027@chacuo.net");
            message.setSubject("您有订单未支付,请按时支付");
            message.setText("哈哈这是主题..............................");
            mailSender.send(message);

        } catch (Exception e) {
            System.out.println("发送简单文本文件-发生异常");
        }
    }

    /**
     * 发送html文本
     *
     * @param
     */
    @Async
    public void sendHTMLMail(EmailRequest request) {
        try {
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper messageHelper = new MimeMessageHelper(message, true, "utf-8");
            messageHelper.setFrom("18108402266@163.com");
            messageHelper.setTo("rctxiw63027@chacuo.net");
            messageHelper.setSubject("欢迎访问");
            messageHelper.setText("<a href='www.baidu.com'>百度</a>", true);
            mailSender.send(message);
        } catch (Exception e) {
        }
    }

    public void sendAttachmentsMail(EmailRequest request) {
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper messageHelper;
        try {
            messageHelper = new MimeMessageHelper(message, true);
            messageHelper.setFrom(request.getFrom());
            messageHelper.setTo(request.getTo());
            messageHelper.setSubject(request.getSubject());
            messageHelper.setText(request.getContent(), true);
            //携带附件
            FileSystemResource file = new FileSystemResource(request.getFilePath());
            String fileName = request.getFilePath().substring(request.getFilePath().lastIndexOf(File.separator));
            messageHelper.addAttachment(fileName, file);
            mailSender.send(message);
        } catch (Exception e) {
            System.err.println("发送邮件异常：" + e.getMessage());
        }
    }
}
